package com.coda.app.interceptor;

import com.coda.context.BaseContext;
import com.coda.properties.JwtAppProperties;
import com.coda.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenAppInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtAppProperties jwtAppProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截的是controller方法还是其他资源
        if (!(handler instanceof HandlerMethod)){
            //当前拦截到的方法不是动态方法直接放心
            return true;
        }

        try {
            //从请求头中获取token
            String token = request.getHeader(jwtAppProperties.getUserTokenName());

            //校验令牌
            log.info("app用户校验令牌");
            Claims claims = JwtUtil.parseJWT(jwtAppProperties.getUserSecretKey(), token);
            Long appId = Long.valueOf(claims.get("appId").toString());
            log.info("当前app用户id为：{}",appId);
            //将appid存入线程中
            BaseContext.setCurrentId(appId);
            return true;
        } catch (NumberFormatException e) {
            //不通过返回状态码
            response.setStatus(401);
            return false;
        }
    }
    /**
     * 清理用户信息
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
